<template>
    <div class="detail-form" v-if="loadingFinish" >
      <Form :model="formInfo" ref="formInfo" class="ivu-form-no-margin-bottom form" :rules="rule" :label-width="120">
        <Row :gutter="32" class="code-row-bg">
          <Col span="12" style="border: none">
            <FormItem prop="travelPositionCode" label="差标职级编码">
              <Input
                v-model="formInfo.travelPositionCode"
                :maxlength="50"
                style="width: 100%" 
                placeholder="请输入差标职级编码"
                clearable
              ></Input>
            </FormItem>
          </Col>
          <Col span="12" style="border: none">
            <FormItem prop="travelPositionName" label="差标职级名称">
              <Input placeholder="请输入差标职级名称" clearable :disabled="disabled" v-model.trim="formInfo.travelPositionName" :maxlength="50" style="width: 100%"></Input>
            </FormItem>
          </Col>  
          <Col span="12" style="border: none" v-if="isPlatformAdmin">
            <FormItem prop="tenantCode" label="所属租户">
              <Select
                :disabled="!!formInfo.id"
                label-in-value
                filterable
                :value="formInfo.tenantCode"
                style="width: 100%"
                clearable
                @on-change="
                  ({ label = '', value = '' } = {}) => {
                    formInfo.tenantCode = value.trim();
                    formInfo.tenantName = label.trim();
                  }
                "
              >
                <Option v-for="tenant in tenantList" :value="tenant.tenantCode" :key="tenant.id">
                  {{ tenant.tenantName }}
                </Option>
              </Select>
            </FormItem>
          </Col> 
          <Col span="12" style="border: none">
            <FormItem prop="ouNames" label="归属公司">
              <Input placeholder="请输入归属公司" clearable :disabled="disabled" v-model.trim="formInfo.ouNames" :maxlength="50" style="width: 100%"></Input>
            </FormItem>
          </Col> 
          <Col span="12" style="border: none" v-if="formInfo.id">
            <FormItem prop="enabled" :label="$t('common.status')">
              <RadioGroup v-model="formInfo.enabled" size="small">
                <Radio :label="'1'">
                  <span>{{ $t('common.enable') }}</span>
                </Radio>
                <Radio :label="'0'">
                  <span>{{ $t('common.disable') }}</span>
                </Radio>
              </RadioGroup>
            </FormItem>
          </Col> 
          <!-- <Col span="24" style="border: none">
            <FormItem :label="$t('common.describe')">
              <Input
              placeholder="请输入描述"
                type="textarea"
                :rows="1"
                v-model="formInfo.remark"
                :maxlength="100"
                style="width: 100%"
                clearable
              ></Input>
            </FormItem>
          </Col> -->
          <Col span="24">
            <FormItem prop="enabled" label="关联的差标">
                <Table :columns="travelStandardColumns" :data="travelStandardData" border></Table>
            </FormItem>
          </Col>
        </Row> 
      </Form>
    </div>
  </template>
  <script>
  import tenantAPI from "@/api/tenantApi.js";
import { apiStandardPositionAdd, apiStandardPositionUpdate } from '@api/trip/standard/standardPosition.js';
import debounce from "lodash/debounce";
import { mapGetters } from "vuex";
  export default {
    name: 'trip-standard-position-manager-detail',
    components: { 
    },
    props: { 
      StandardPosition: {
        type: Object, 
      },
      disabled:{
        type:Boolean,
        default:false, 
        required: false,
      }
    },
    data() { 
      return { 
        loadingFinish:false, 
        tenantList: [], // 租户列表 
        travelStandardData:[],// 差旅标准列表
        formInfo: { 
          // 差标编码
          travelPositionCode: '',
          // 差标名称
          travelPositionName: '',
          // customerCode 客户编码
          // customerName 客户名称
          // ouCodes 客商编码
          // ouNames 客商名称 
          ouNames:'',
          // isApplyBill: '0', // 是否需要申请单
          // isBudget:'0', // 是否预算管控
          // 所属租户
          // tenantCode: '',
          // tenantName: '',
          //差标状态
          enabled: '1', 
        },
        rule: {
          travelPositionCode: [{ required: true, message: '请输入差标职级编码', trigger: 'blur' }], 
          travelPositionName: [{ required: true, message: '请输入差标职级名称', trigger: 'blur' }], 
          // isApplyBill:[{ required: true, message: '请选择是否需要申请单', trigger: 'blur' }],// 是否需要申请单
          // isBudget:[{ required: true, message: '请选择是否需要预算管控', trigger: 'blur' }], // 是否预算管控 
          // 'train':[{ required: true, validator: trainValidate, trigger: 'blur' }], //  
        },
        actions: [
          {
            /**
              text: "按钮label",
              theme: "warning",
              icon: "plus-round",
              action: "actionName1", //可以通过 SetActionsState  actionName1 的 state 来设置这个按钮是否 loading
          */
            text: this.$t('common.save'),
            theme: 'primary',
            action:"save",
            handle: debounce(()=>this.handleSave(),300),
            loading: false
          },
          {
            text: this.$t('common.close'),
            handle: () => {
              this.$emit('Close')
            }
          }
        ],
        travelStandardColumns:[
        {
              title: '差标编码',
              key: 'travelStandardCode',
              width: 180,
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title =  params.row['travelStandardCode'] 
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title
                    }
                  },
                  title
                )
              }
            },
            {
              title: '差标名称',
              key: 'travelStandardName',
              width: 280,
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: params.row['travelStandardName']
                    }
                  },
                  params.row['travelStandardName']
                )
              }
            },
            {
              title: '所属租户',
              key: 'tenantCode',
              align: 'center',
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title = this.tenantByName[params.row['tenantCode']] + `(${params.row['tenantCode']})`
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title 
                    }
                  },
                  title
                )
              }
            }, 
            {
              title: '归属公司',
              key: 'ouNames',
              align: 'center',
              resizable:true,
              sortable: 'custom',
              render: (h, params) => {
                let title = params.row['ouNames'] 
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: title 
                    }
                  },
                  title
                )
              }
            }, 
            {
              title: this.$t('common.describe'), // 备注 改为 描述
              key: 'remark',
              minWidth: 120,
              render: (h, params) => {
                return h(
                  'div',
                  {
                    attrs: {
                      class: 'ivu-table-cell ivu-table-cell-ellipsis',
                      title: params.row.remark
                    }
                  },
                  params.row.remark
                )
              }
            },
        ]
      }
    },
    computed: { 
      ...mapGetters(['isPlatformAdmin']), 
    },
    created: function() {
      this.tenantList = []
      this.$Spin.show({
          render: (h) => {
              return h('div', [
                  h('Icon', {
                      'class': 'spin-icon-load',
                      props: {
                          type: 'ios-loading',
                          size: 18
                      }
                  }),
                  h('div', '加载中...')
              ])
          }
      });
      //#region  sidelipPage 配置
      if (this.id) {
        this.$emit('SetTitle', '编辑差标职级配置')
      } else {
        this.$emit('SetTitle', '新增差标职级配置')
      }
      this.$emit('SetPageWidth', 700)
      this.$emit('SetPageActions', this.actions)
      //#endregion
      this.init() 
    },
    mounted: function() {},
    methods: {  
      init() { 
        console.log('this.StandardPosition :>> ', this.StandardPosition);
        if (this?.StandardPosition?.id) {
           this.formInfo = Object.assign({},this.StandardPosition);
        }
        this.$Spin.hide();
        this.loadingFinish = true;  
        if(this.isPlatformAdmin){  
           tenantAPI.queryTenantList().then(data => { 
            this.tenantList = data 
          })
          this.$set(this.formInfo,'tenantCode',this.formInfo?.tenantCode);
          this.$set(this.rule,'tenantCode',[{ required: true, message: '请选择所属租户', trigger: 'blur' }]); 
        }
      },
      handleSave() {
        this.$refs['formInfo'].validate(valid => {
          if (valid) {
            this.actions[0].loading = true
            if (this.formInfo.id) {
              let param = this.formInfo
              apiStandardPositionUpdate(param)
                .then(data => {
                  console.log('保存失败 :>> ', data);
                  this.actions[0].loading = false
                  if (data.code === "0") {
                    this.$message.success({
                      content: '保存成功',
                      duration: 3
                    });
                    this.$emit('Close', true); 
                  } else {
                    this.$message.error({
                      content: data.message || "保存失败",
                      duration: 3
                    });
                  }  
                })
                .catch(data => {
                  this.actions[0].loading = false 
                })
            } else {
              let param = this.formInfo; 
              apiStandardPositionAdd(param)
                .then(data => { 
                  this.actions[0].loading = false 
                  if (data.code === "0") {
                    this.$message.success({
                      content: '保存成功',
                      duration: 3
                    });
                    this.$emit('Close', true); 
                  } else {
                    this.$message.error({
                      content: data.message || "保存失败",
                      duration: 3
                    });
                  } 
                })
                .catch(data => {
                  this.actions[0].loading = false
                })
            } 
          }
        })
      },
   
    }
  }
  </script>
  <style scoped lang="less">
  .detail-form {
    background: #f4f6fd;
    .form {
      background: #fff;
      padding: 24px 24px 12px 24px;
      .ivu-row {
        margin-bottom: 0px;
        .last-item {
          margin-bottom: 0px;
        }
      }
      .form-title {
        display: block;
        font-size: 16px;
        color: #333333;
        letter-spacing: 0;
        font-weight: 600;
      }
    }
  }
  </style>
  